package com.hotel.product.service.impl;

import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.SystemConfig;
import com.hotel.common.util.JwtUtil;
import com.hotel.common.vo.R;
import com.hotel.product.mapper.UserLevelMapper;
import com.hotel.user.entity.*;
import com.hotel.product.mapper.PurchaseMapper;
import com.hotel.product.service.PurchaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author KK
 * @since 2024-06-18
 */
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private UserLevelMapper userLevelMapper;
    @Override
    public ResponseDTO<String> purchaseProduct(Purchase purchase, HttpServletRequest request) {
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        //解析token
        int id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        QueryWrapper<UserLevel> levelQueryWrapper = new QueryWrapper<>();
        levelQueryWrapper.eq("user_id", id);
        UserLevel userLevel = userLevelMapper.selectOne(levelQueryWrapper);
        if (userLevel.getGrowths()< purchase.getPrice()){
            return  new ResponseDTO<>(500,"积分余额不足",null);
        }else {
            //你看我打个断点
            //扣除积分
            userLevel.setGrowths((int) (userLevel.getGrowths()-purchase.getPrice()));
            //将扣除之后的积分存到数据库
            userLevelMapper.update(userLevel,levelQueryWrapper);
            Purchase purchase2 = new Purchase();
            purchase2.setProductId(purchase.getId());
            purchase2.setUserId(id);
            purchase2.setQuantity(1);
            purchase2.setPrice(purchase.getPrice());
            purchase2.setTimestamp(System.currentTimeMillis());//时间戳
            purchaseMapper.insert(purchase2);
            return new ResponseDTO<>(200,"购买成功",null);
        }

    }
}
